#include "StdAfx.h"
#include "DatabaseThread.h"
#include "..\Infobus\ConnectionString.h"

#import "msado15.dll" rename_namespace("ADODB") rename("EOF", "ADOEOF")  

ADODB::_ConnectionPtr cn;  

DatabaseThread::DatabaseThread()
: cnOpen(false)
{
  OutputDebugString("DatabaseThread::DatabaseThread()\n");
}

DatabaseThread::~DatabaseThread()
{
  OutputDebugString("DatabaseThread::~DatabaseThread()\n");

}

void DatabaseThread::run()
{
  OutputDebugString("DatabaseThread::run()\n");
  HRESULT hr;

  open();

  while (!isTerminated()) {
    try {
      if (waitForLock()) {
        OutputDebugString("Writes to database...\n");
        bstr_t sql = "INSERT INTO SAMPLE_DATA (DATA) VALUES ('Data is being written')";
        hr = cn->Execute(sql, NULL, ADODB::adExecuteNoRecords);
        if (S_OK != hr) throw("Data not written properly");
        try { hr = cn->CommitTrans(); } catch (...) { }
        releaseLock();
      }
      sleep(1000);
    } catch (...) {
      reopen();
    }
  }
}

void DatabaseThread::open()
{
  OutputDebugString("DatabaseThread::open()\n");

  HRESULT hr;
  bstr_t cns;
    
  ::CoInitialize(NULL);

  hr = cn.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
  if (S_OK != hr) throw("CreateInstance failed");
  cns = bstr_t(CONNECTSTRING);

  while (!cnOpen) {
    try {
      hr = cn->Open(cns, L"", L"", -1);  
      if (S_OK != hr) throw("Database not opened properly");
      cnOpen = true;
    } catch (_com_error& e) {
      TCHAR buffer[0x1000] = { 0 };        
      sprintf(buffer, "%s [%ld]\n", e.ErrorMessage(), e.Error());  
      OutputDebugString(buffer);
      try { cn->Close(); } catch (...) { }
      cnOpen = false;
    }
    if (!cnOpen) sleep(1000);
  }
}

void DatabaseThread::reopen()
{
  OutputDebugString("DatabaseThread::reopen()\n");

  try { cn->Close(); } catch (...) { }
  cnOpen = false;

  open();
}
